//
//  HTHorizontalSelectionList.m
//  Hightower
//
//  Created by Erik Ackermann on 7/31/14.
//  Copyright (c) 2014 Hightower Inc. All rights reserved.
//

#import "HTHorizontalSelectionList.h"
#import "LZHorizontalView.h"
#import "UIScrollView+LZContentOffset.h"
#import "Masonry.h"
 

@interface HTHorizontalSelectionList ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray *buttons;
@property (nonatomic, strong) NSMutableArray *lines;

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIImageView *selectionIndicatorBar;
@property (nonatomic, strong) UIView *markLine;

@property (nonatomic, strong) NSLayoutConstraint *centerSelectionIndicatorConstraint;

@property (nonatomic, strong) UIView *bottomTrim;
@property (nonatomic, strong) NSMutableDictionary *buttonColorsByState;

@property (nonatomic, strong) UIColor *bottomTrimColor;
@property (nonatomic) UIEdgeInsets buttonInsets;

@end

#define kHTHorizontalSelectionListHorizontalMargin 20
#define kHTHorizontalSelectionListInternalPadding 20
#define kHTHorizontalSelectionListSelectionIndicatorHeight 5
#define kHTHorizontalSelectionListTrimHeight 0.5

@implementation HTHorizontalSelectionList

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];

        _scrollView = [[LZHorizontalView alloc] init];
//        _scrollView.backgroundColor = UIColorFromRGB(0xf9f7f7, 1);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.scrollsToTop = NO;
        _scrollView.canCancelContentTouches = YES;
        _scrollView.translatesAutoresizingMaskIntoConstraints = NO;

        [self addSubview:_scrollView];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_scrollView]|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_scrollView)]];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_scrollView]|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_scrollView)]];

        _contentView = [[UIView alloc] init];
        _contentView.translatesAutoresizingMaskIntoConstraints = NO;
        [_scrollView addSubview:_contentView];

        [self addConstraint:[NSLayoutConstraint constraintWithItem:_contentView
                                                         attribute:NSLayoutAttributeTop
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:self
                                                         attribute:NSLayoutAttributeTop
                                                        multiplier:1.0
                                                          constant:0.0]];

        [self addConstraint:[NSLayoutConstraint constraintWithItem:_contentView
                                                         attribute:NSLayoutAttributeBottom
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:self
                                                         attribute:NSLayoutAttributeBottom
                                                        multiplier:1.0
                                                          constant:0.0]];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_contentView)]];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_contentView)]];

        _bottomTrim = [[UIView alloc] init];
        _bottomTrim.backgroundColor = UIColorFromRGB(0xcccccc, 1);
        _bottomTrim.translatesAutoresizingMaskIntoConstraints = NO;
        _bottomTrim.hidden = YES;
        [self addSubview:_bottomTrim];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[_bottomTrim]-10-|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:nil
                                                                       views:NSDictionaryOfVariableBindings(_bottomTrim)]];

        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_bottomTrim(height)]|"
                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                     metrics:@{@"height" : @(kHTHorizontalSelectionListTrimHeight)}
                                                                       views:NSDictionaryOfVariableBindings(_bottomTrim)]];

        self.buttonInsets = UIEdgeInsetsMake(5, 5, 5, 5);

        _buttons = [NSMutableArray array];
        _lines = [NSMutableArray array];

        _selectionIndicatorBar = [[UIImageView alloc] init];
        _selectionIndicatorBar.image = [UIImage imageNamed:@"lz_mycoupons_headermark"];
        _selectionIndicatorBar.translatesAutoresizingMaskIntoConstraints = NO;
        _selectionIndicatorBar.hidden = YES;

    }
    return self;
}

#pragma mark - Public Methods

- (void)setScrollViewColor:(UIColor *)color {
    self.scrollView.backgroundColor = color;
}

- (void)reloadData {
    for (UIButton *button in self.buttons) {
        [button removeFromSuperview];
    }

    for (UIView *line in self.lines) {
        [line removeFromSuperview];
    }
    
    [self.selectionIndicatorBar removeFromSuperview];
    [self.buttons removeAllObjects];

    NSInteger totalButtons = [self.dataSource numberOfItemsInSelectionList:self];

    if (totalButtons < 1) {
        return;
    }
    else if (totalButtons == 1) {
        [self configOneButton];
    }
    else if (totalButtons == 2) {
        [self configTwoButton];
    }
    else {
        [self configMoreButton:totalButtons];
    }
    
}

- (void)configOneButton {
    NSString *buttonTitle = [self.dataSource selectionList:self titleForItemWithIndex:0];
    
    UIButton *button = [self selectionListButtonWithTitle:buttonTitle];
    [self.contentView addSubview:button];
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[button]-0-|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:@{@"margin" : @(kHTHorizontalSelectionListHorizontalMargin)}
                                                                               views:NSDictionaryOfVariableBindings(button)]];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:button
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeHeight
                                                                multiplier:1.0
                                                                  constant:0.0]];
    // _contentView的宽高 和_scrollView的宽高相等的约束
    [_scrollView addConstraint:[NSLayoutConstraint constraintWithItem:_contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_scrollView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    
    [self.buttons addObject:button];

}

- (void)configTwoButton {
    
    // 第一个按钮
    NSString *buttonTitle1 = [self.dataSource selectionList:self titleForItemWithIndex:0];
    UIButton *button1 = [self selectionListButtonWithTitle:buttonTitle1];
    [self.contentView addSubview:button1];
    
    // 第二个按钮
    NSString *buttonTitle2 = [self.dataSource selectionList:self titleForItemWithIndex:1];
    UIButton *button2 = [self selectionListButtonWithTitle:buttonTitle2];
    [self.contentView addSubview:button2];
    
    // 线
    UIView * lineView = [[UIView alloc] init];
    lineView.backgroundColor = UIColorFromRGB(0xdddddd, 1);
    lineView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:lineView];
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[button1]-0-[lineView(0.5)]-0-[button2(==button1)]-0-|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:@{@"margin" : @(kHTHorizontalSelectionListHorizontalMargin)}
                                                                               views:NSDictionaryOfVariableBindings(button1,lineView,button2)]];
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[lineView]-20-|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:nil
                                                                               views:NSDictionaryOfVariableBindings(button1, lineView, button2)]];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:button1
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeHeight
                                                                multiplier:1.0
                                                                  constant:0.0]];
    
    [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:button2
                                                                 attribute:NSLayoutAttributeHeight
                                                                 relatedBy:NSLayoutRelationEqual
                                                                    toItem:self.contentView
                                                                 attribute:NSLayoutAttributeHeight
                                                                multiplier:1.0
                                                                  constant:0.0]];
    // _contentView的宽高 和_scrollView的宽高相等的约束
    [_scrollView addConstraint:[NSLayoutConstraint constraintWithItem:_contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_scrollView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0]];
    
    [self.buttons addObject:button1];
    [self.buttons addObject:button2];
    
    UIButton *selectedButton = self.buttons[self.selectedButtonIndex];
    selectedButton.selected = YES;
    
    [self.contentView addSubview:self.selectionIndicatorBar];
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_selectionIndicatorBar(height)]-7-|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:@{@"height" : @(kHTHorizontalSelectionListSelectionIndicatorHeight)}
                                                                               views:NSDictionaryOfVariableBindings(_selectionIndicatorBar)]];
    
    [self alignSelectionIndicatorWithButton:selectedButton];
    
    [self bringSubviewToFront:self.bottomTrim];
    [self updateConstraintsIfNeeded];
}

- (void)configMoreButton:(NSInteger)count {
    UIButton *previousButton;
    
    for (NSInteger index = 0; index < count; index++) {
        NSString *buttonTitle = [self.dataSource selectionList:self titleForItemWithIndex:index];
        
        UIButton *button = [self selectionListButtonWithTitle:buttonTitle];
        [self.contentView addSubview:button];
        
        UIView * lineView = [[UIView alloc] init];
        lineView.backgroundColor = UIColorFromRGB(0xdddddd, 1);
        lineView.translatesAutoresizingMaskIntoConstraints = NO;
        
        if (previousButton) {
            
            [self.contentView addSubview:lineView];
            [self.lines addObject:lineView];
            
            NSString *constraints_H;
            if (self.isEqualWidth) {
                constraints_H = @"H:[previousButton]-padding-[lineView(1)]-padding-[button(==previousButton)]";
            }
            else {
                constraints_H = @"H:[previousButton]-padding-[lineView(1)]-padding-[button]";
            }
            
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraints_H
                                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                                     metrics:@{@"padding" : @(self.isEqualWidth?0:kHTHorizontalSelectionListInternalPadding)}
                                                                                       views:NSDictionaryOfVariableBindings(previousButton, lineView, button)]];
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[lineView]-20-|"
                                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                                     metrics:nil
                                                                                       views:NSDictionaryOfVariableBindings(previousButton, lineView, button)]];
        } else {
            NSString *constraints_H;
            if (self.isEqualWidth) {
                constraints_H = [NSString stringWithFormat:@"H:|-margin-[button(%f)]",self.equalWidth];
            }
            else {
                constraints_H = @"H:|-margin-[button]";
            }
            [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraints_H
                                                                                     options:NSLayoutFormatDirectionLeadingToTrailing
                                                                                     metrics:@{@"margin" : @(self.isEqualWidth?0:kHTHorizontalSelectionListHorizontalMargin)}
                                                                                       views:NSDictionaryOfVariableBindings(button)]];
        }
        
        [self.contentView addConstraint:[NSLayoutConstraint constraintWithItem:button
                                                                     attribute:NSLayoutAttributeHeight
                                                                     relatedBy:NSLayoutRelationEqual
                                                                        toItem:self.contentView
                                                                     attribute:NSLayoutAttributeHeight
                                                                    multiplier:1.0
                                                                      constant:0.0]];
        
        previousButton = button;
        [self.buttons addObject:button];
    }
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[previousButton]-margin-|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:@{@"margin" : @(self.isEqualWidth?0:kHTHorizontalSelectionListHorizontalMargin)}
                                                                               views:NSDictionaryOfVariableBindings(previousButton)]];
    if (count > 0) {
        UIButton *selectedButton = self.buttons[self.selectedButtonIndex];
        selectedButton.selected = YES;
        
        [self.contentView addSubview:self.selectionIndicatorBar];
        [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_selectionIndicatorBar(height)]-7-|"
                                                                                 options:NSLayoutFormatDirectionLeadingToTrailing
                                                                                 metrics:@{@"height" : @(kHTHorizontalSelectionListSelectionIndicatorHeight)}
                                                                                   views:NSDictionaryOfVariableBindings(_selectionIndicatorBar)]];
        
        [self alignSelectionIndicatorWithButton:selectedButton];
    }
    
    [self bringSubviewToFront:self.bottomTrim];
    [self updateConstraintsIfNeeded];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (!self.buttons.count) {
        [self reloadData];
    }    
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    [self.scrollView setLanguageContentOffset];
}

#pragma mark - Private Methods

- (UIButton *)selectionListButtonWithTitle:(NSString *)buttonTitle {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.contentEdgeInsets = self.buttonInsets;
    
    [button setTitle:buttonTitle forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0x333333, 1) forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0xff7a21, 1) forState:UIControlStateSelected];
    
    for (NSNumber *controlState in [self.buttonColorsByState allKeys]) {
        [button setTitleColor:self.buttonColorsByState[controlState] forState:controlState.integerValue];
    }
    
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button sizeToFit];

    [button addTarget:self action:@selector(buttonWasTapped:) forControlEvents:UIControlEventTouchUpInside];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    
    return button;
}

- (void)setupSelectedButton:(UIButton *)selectedButton oldSelectedButton:(UIButton *)oldSelectedButton {
//    [self.contentView removeConstraint:self.centerSelectionIndicatorConstraint];
    [self alignSelectionIndicatorWithButton:selectedButton];
    [self layoutIfNeeded];
}

- (void)alignSelectionIndicatorWithButton:(UIButton *)button {
//    self.centerSelectionIndicatorConstraint = [NSLayoutConstraint constraintWithItem:self.selectionIndicatorBar
//                                                                         attribute:NSLayoutAttributeCenterX
//                                                                         relatedBy:NSLayoutRelationEqual
//                                                                            toItem:button
//                                                                         attribute:NSLayoutAttributeCenterX
//                                                                        multiplier:1.0
//                                                                          constant:0.0];
//    [self.contentView addConstraint:self.centerSelectionIndicatorConstraint];
    
    if (_markLine == nil) {
        _markLine = [[UIView alloc] init];
        _markLine.backgroundColor = UIColorFromRGB(0xff7a21, 1);
        [self.contentView addSubview:self.markLine];
        
        [self.markLine mas_makeConstraints:^(MASConstraintMaker *make) {
            if (self.buttons.count >2) {
                make.leading.equalTo(button).offset(-kHTHorizontalSelectionListHorizontalMargin);
                make.trailing.equalTo(button).offset(kHTHorizontalSelectionListHorizontalMargin);
            }
            else {
                make.leading.and.trailing.equalTo(button);
            }
            
            make.height.equalTo(3);
            make.bottom.equalTo(self.contentView.mas_bottom);
        }];
    }
    else {
        [self.markLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            if (self.buttons.count >2) {
                make.leading.equalTo(button).offset(-kHTHorizontalSelectionListHorizontalMargin);
                make.trailing.equalTo(button).offset(kHTHorizontalSelectionListHorizontalMargin);
            }
            else {
                make.leading.and.trailing.equalTo(button);
            }
            
            make.height.equalTo(3);
            make.bottom.equalTo(self.contentView.mas_bottom);
        }];
    }
    

}

#pragma mark - Action Handlers

- (void)buttonWasTapped:(UIButton*)sender {
    self.isClickButton = YES;
    NSInteger index = [self.buttons indexOfObject:sender];
    if (index != NSNotFound) {
        
        [self.scrollView scrollRectToVisible:CGRectInset(sender.frame, -kHTHorizontalSelectionListHorizontalMargin, 0)
                                    animated:YES];
        
        if (index == self.selectedButtonIndex) {
            return;
        }
        
        UIButton *oldSelectedButton = self.buttons[self.selectedButtonIndex];
        oldSelectedButton.selected = NO;
        
        self.selectedButtonIndex = index;

        sender.selected = YES;

        [self layoutIfNeeded];
        
        [self setupSelectedButton:sender oldSelectedButton:oldSelectedButton];
        
                
        if ([self.delegate respondsToSelector:@selector(selectionList:didSelectButtonWithIndex:)]) {
            [self.delegate selectionList:self didSelectButtonWithIndex:index];
        }
    }
}

@end
